import React, { PropTypes, Component } from 'react'
import fetch from 'isomorphic-fetch'
import { Link } from 'react-router'
import {myAjax,ROOTURL} from './../publicAPI/publicAPI'
import NavLink from './NavLink'
import TextInput from './TextInput'
import SelectInput from './SelectInput'
import FileInput from './FileInput'
import CheckboxInput from './CheckboxInput'
import ImageWithState from './ImageWithState'
import Table from './Table'
import style from './BannerM.css'

class BannerM extends Component {

  constructor (props, context) {
      super(props, context);
      console.log("初始化");
      this.state = {
        previewImgFiles: [],
            previewImgUrl: [],
            hasBeenMounted: false,
            hompage_slider:[],
            delete : false,
            deleteId:-1,
            };
       this.handleImgUpload.bind(this);
       this.handlesave.bind(this);

       this.getlist.bind(this);
        // 初始化状态
  }

  componentWillMount() {
    this.getlist();

  }
  componentDidMount() {
      console.log("安装成功")
  	//1

  }

  getlist(){

    var _this=this;
    _this.state.hashed=[];
    console.log("清空当前状态");
      console.log("将安装", this.props.params.id);

      var Geturl=ROOTURL+'config/dynamic/public/get.api';
      var data={
      k:'hompage_slider'
};
   myAjax(Geturl, "POST",data ,function(data) {
        console.log(data);
        var need_hashed=JSON.parse(data.v);


     _this.setState({
                 hompage_slider:need_hashed
                });
     console.log("hompage_slider",_this.state.hompage_slider)

        }, function(err) {/*location.href="/"*/})


}

    handleImgUpload(files) {
        var fileUrl = [];
        var _this = this;

        files.map(file=> {
            var freader = new FileReader();
            freader.readAsDataURL(file);
            freader.onload = function (e) {
                fileUrl.push({ src :e.target.result});
                //因异步操作存在多次渲染，待修改
                _this.setState(Object.assign({}, this.state, {
                    previewImgFiles: files,
                    previewImgUrl: fileUrl
                }));
            };

        });
    }
    deleteImg(key) {

        var newFiles = this.state.hompage_slider;

        var index_hashed=this.state.hompage_slider[key].img;
        newFiles.splice(key, 1);
      var delete_url=ROOTURL+'/asset/images/delete.api';
      var delete_data={
        hashed:index_hashed
      }
       myAjax(delete_url, "POST", delete_data, function(data) {

        }, function(err) {/*location.href="/"*/})
       var end_data=JSON.stringify(newFiles)
 var data={
          k:'hompage_slider',
          v:end_data
        }
        var Seturl=ROOTURL+'/config/dynamic/public/set.api';
        myAjax(Seturl, "POST", data, function(data) {
        console.log("这一部",data)
          if(data.k!=null) {
           location=location;
          }
          else{
            alert("删除失败");
          }
        }, function(err) {/*location.href="/"*/})
 }
    tHead() {

    var data = [
        {name: "图片"},
        {name: "链接"},
        {name: "操作"},
      ]
    const _headArr = []
    const _width = {
      "0" : "30%",
      "1" : "50%",
      "2" : "20%",
    }
    _headArr.push(data.map((item, index) => <th style={{width: _width[index]}} role="1" key={index}>{item.name}</th>))
    return _headArr;
  }
  //render tbody
  tBody() {
    var _this=this;
    var i;
    var array=new Array();
    for(i=0;i<this.state.hompage_slider.length;i++){
      if(_this.state.hompage_slider[i].img!=""){
            array[i]= (<tr key={i}>
                <td><img src={ROOTURL + 'asset/images/get.api?hashed='+_this.state.hompage_slider[i].img} style={{verticalAlign: 'middle',lineHeight:'132px'}}/></td>
                <td><input type="text" ref={"img"+i} onChange={this.handlechange.bind(this,i)} className={style["comLineHeight"]} defaultValue={_this.state.hompage_slider[i].href}/></td>
                <td><span key={'sp'+i} onClick={this.handleDelete.bind(this,i)}><a>删除</a></span></td>
                </tr>)
      }
      else{


      }
    }
    return array;

}
handlechange(i){
  var _this=this;
  var hompage_slider=_this.state.hompage_slider;

  _this.state.hompage_slider[i].href=_this.refs["img"+i].value;
  _this.setState({
    hompage_slider:_this.state.hompage_slider
  })
}

  handleDelete(i){
        this.setState({
            delete: !this.state.delete,
            deleteId : i
        })
    }

  handleurlsave(){

    var _this=this;
    var hompage_slider=_this.state.hompage_slider;
    console.log("url",_this.state.hompage_slider)
      var Seturl=ROOTURL+'config/dynamic/public/set.api';
      var end_data={
        k:'hompage_slider',
        v:JSON.stringify(hompage_slider)
      }
        myAjax(Seturl, "POST", end_data, function(data) {
       console.log(data)
          if(data.v!="") {
            alert("保存成功");
            this.getlist();
          }
        }, function(err) {/*location.href="/"*/})

  }
  handlesave(){
    var _this=this;
    const imgfile_url=this.state.previewImgUrl;
    const imgfiles=this.state.previewImgFiles;
    var j=0;
    for(var i=0;i<imgfiles.length;i++){
    var img=new Image();
    img.src=imgfile_url[i].src;
    const width=img.width;
    const height=img.height;
    console.log(width,height);
    var fd = new FormData();
    var  xhr = new XMLHttpRequest();
      xhr.open("POST", ROOTURL + "asset/images/upload.api?width="+width+"&height="+height+"&noShrink="+true);
      var f =imgfiles[i];
      var fd = new FormData();
      fd.append("file", f);
      xhr.send(fd);
      xhr.onload=function(data){
      console.log(data);
      var status=data.currentTarget.status;
      if(status==200){

                          var imageList = _this.state.previewImgUrl;
                          var imgData = _this.state.previewImgUrl[j];
                          imageList[j] = imgData;
                          imgData.msg = '保存成功';
                          _this.setState({
                          previewImgUrl : imageList
                          });

        j++;
        console.log("获取成功");

        var res=data.currentTarget.response;
        var res_json=JSON.parse(res);
        var res_hashed=res_json.hashed;
        console.log(res_hashed);
        var message={
          img:res_hashed,
          href:""
        }
        var save_data=new Array();
        save_data.push(message);
        console.log("save_data",save_data)
        console.log("此时状态",_this.state.hompage_slider)
        _this.setState(Object.assign({}, this.state, {
                  hompage_slider:_this.state.hompage_slider.concat(save_data)
                }));
        var newstate=JSON.stringify(_this.state.hompage_slider);
        console.log("newstate",newstate)
        var data={
          k:'hompage_slider',
          v:newstate
        }
        var Seturl=ROOTURL+'config/dynamic/public/set.api';
        myAjax(Seturl, "POST", data, function(data) {
          if(data.status==200) {
          this.getlist();
          }
        }, function(err) {/*location.href="/"*/})
     console.log("检查此时状态",_this.state.hompage_slider);
      }
      else{
                var imageList = _this.state.previewImgUrl;
                var imgData = _this.state.previewImgUrl[j];
                imageList[j] = imgData;
                imgData.msg = '保存失败';
                _this.setState({
                previewImgUrl : imageList
                });

        j++;
      }
    }
  }

	}


    render() {
	    return (
<div>
	    	<div className={style["wrap"]} id="tb_img">
	    		<div id="filePicker" className={style["hide"]}></div>
	    		<button id="submit"  className={style.btn_blue} onClick={this.handlesave.bind(this)}>保存</button>
	    		<button id="upload" className={style.btn_blue2}>图片选择上传  <FileInput type="file"
                                                                                        fileClass={style["imgUploader-btn"]}
                                                                                        accept=".jpg,.png,.jpeg,.gif,.bmp"
                                                                                        onChange={(files)=>this.handleImgUpload(files)}/>
                                                                                       </button>

          <span className={style["tips dpib"]} style={{marginLeft:'10px'}}>请选择640*280大小的图片。每次上传和删除图片后，请点击左侧“保存”按钮进行保存</span>
          <h3 className={style["catagory"]}><span>上传图片列表</span></h3>
          <div className={style["img_show_div"]}>
          <ul ref="img" id="fileList" className={style["img_list"]} >
            {this.state.previewImgUrl.length > 0 ? this.state.previewImgUrl.map((img, index)=> {

                            return <ImageWithState liClassName={style["img_list_li"]} imgClassName={style["img_list_li_img"]} src={img.src} stateMsg={img.msg} id={index}/>
                        }) : null}
            </ul>
           </div>


        </div>
        <div className={style["wrap"]} id="tb_main">
          <span id="hint"></span>
          <h3 className={style["catagory"]}>
            <span>首页banner图片管理</span>
          </h3>
           <Table tableClass={style["banner-table"]}tHead={this.tHead.bind(this)()} tBody={this.tBody.bind(this)()}/>
           <div className={style["url_button"]}>
           <button className={style.btn_blue3} onClick={this.handleurlsave.bind(this)}>保存所有链接</button>
           </div>
          </div>
             { this.state.delete ?
                    <div id={style["msgDialog"]}>
                        <div className={style["msgDialog_div"]}><h3 id={style["msgDialog_title"]}>删除提示？</h3><p id={style["msgDialog_content"]}>
                            确认删除？</p>
                            <div className={style["msgDialog_button"]}>
                                <button id={style["msgDialog_yes"]} onClick={this.deleteImg.bind(this,this.state.deleteId)}>确定</button>
                                <button id={style["msgDialog_no"]}
                                        onClick={()=>this.setState({delete: !this.state.delete})}>
                                    取消
                                </button>
                            </div>
                        </div>
                    </div> : null}


</div>

      )
    }
}

 export default BannerM
